<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页 | 亳州客服插件系统v1.0.0</title>
    <link rel="stylesheet" href="../css/room/room.css">
    <!-- 使用 th:src 属性引入本地 JavaScript 文件 -->
    <script th:src="@{/js/jquery/jquery.min.js}"></script>
</head>
<body class="hold-transition skin-blue sidebar-mini" onload="getRooms()">
<header>
    当前登录人员：<span id="userId" th:text="${userId}"></span>
    <br/>
    <br/>
    想要对话人员：
    <select id="otherUser">
        <option value="1001">1001</option>
        <option value="1002">1002</option>
        <option value="1003">1003</option>
        <option value="2001">2001</option>
        <option value="2002">2002</option>
    </select>
    <button onclick="faqiliaotian(document.getElementById('otherUser').value)">发起聊天</button>
    <br/>
    聊天室编号： <span id="roomId"></span>
</header>
<main class="container">
    <div class="chat-container">
        <div class="left-menu" id="leftMenu">
            <!-- 左侧菜单内容 -->
        </div>
        <div class="output" id="output">
            <!-- 聊天内容 -->
        </div>
    </div>
    <div id="emojiPicker" class="emoji-picker">
        <!-- 表情选择框 -->
    </div>
    <div class="input-group">
        <div class="input-group-btn">
            <button class="image-button" type="button" onclick="showEmojis();">
                <i class="fa fa-smile-o"></i>
            </button>
            <button class="image-buttonimg68" type="button" onclick="uploadImage();">
                <i class="fa fa-picture-o"></i>
            </button>
            <button class="image-buttonimg69" type="button" onclick="startVoiceCall();">
                <i class="fa fa-microphone"></i>
            </button>
        </div>
    </div>
    <div class="input-group">
        <div id="message" contenteditable="true" class="message-input" placeholder="待发信息"
             onkeydown="en(event);"></div>
        <button class="send-btn" type="button" onclick="doSend();">发送</button>
    </div>
</main>

<script language="javascript" type="text/javascript">
    if (typeof(EventSource) !== "undefined") {
        const eventSource = new EventSource("/events");

        eventSource.onmessage = function(event) {
            onMessage(event);
        };

        eventSource.onerror = function(event) {
            console.error("EventSource failed.");
            if (event.target.readyState === EventSource.CLOSED) {
                console.log("Connection closed.");
            }
        };
    } else {
        console.warn("Your browser does not support Server-Sent Events.");
    }

    function formatDate(now) {
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        return year + "-" + (month = month < 10 ? ("0" + month) : month) + "-" + (date = date < 10 ? ("0" + date) : date) +
            " " + (hour = hour < 10 ? ("0" + hour) : hour) + ":" + (minute = minute < 10 ? ("0" + minute) : minute) + ":" + (
                second = second < 10 ? ("0" + second) : second);
    }

    var leftMenu;
    var output;
    var websocket;

    function getRooms() {
        var userId = document.getElementById('userId').innerText;
        var data = {
            user1: userId
        };
        $.ajax({
            url: '/socket/getRooms',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (response) {
                var jsonObjectS = response.data;
                var otherUser = "";
                $("#leftMenu").append("<div style='text-align:left;font-size: 20px; height: 30px;background-color: #cdedcb;'>聊天列表</div>");
                for (let i = 0; i < jsonObjectS.length; i++) {
                    otherUser = (userId == jsonObjectS[i].user1) ? jsonObjectS[i].user2 : jsonObjectS[i].user1;
                    var div = "<div style='text-align:left;font-size: 15px; height: 30px' onclick='faqiliaotian(" + otherUser + ")' >" + otherUser + "</div>";
                    $("#leftMenu").append(div);
                }
                if (jsonObjectS.length > 0) {
                    faqiliaotian((userId == jsonObjectS[0].user1) ? jsonObjectS[0].user2 : jsonObjectS[0].user1);
                }
            },
            error: function (xhr, status, error) {
                console.error('错误:', error);
            }
        });
    }

    function faqiliaotian(otherUser) {
        $("#output").empty();
        var userId = document.getElementById('userId').innerText;
        var data = {
            user1: userId,
            user2: otherUser
        };
        $.ajax({
            url: '/socket/createRoom',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (response) {
                document.getElementById('roomId').innerText = response.data.roomid;
                // 获取聊天对话框消息后，输出到output
            },
            error: function (xhr, status, error) {
                console.error('错误:', error);
            }
        });
    }



    function onMessage(evt) {
        var jsonObject = JSON.parse(evt.data);
        if (jsonObject.total !== undefined) {
            var jsonObjectS = jsonObject.list;
            for (let i = 0; i < jsonObjectS.length; i++) {
                expMessage(jsonObjectS[i]);
            }
        } else {
            expMessage(jsonObject);
        }
    }

    function expMessage(jsonObject) {
        var userId = document.getElementById('userId').innerText;
        var respUId = jsonObject.userId;
        var textAlign = userId == respUId ? 'right' : 'left';
        var messageTime = '<span class="message-time" style="color: #999; text-align: ' + textAlign + '">' + respUId + "  " + formatDate(new Date(jsonObject.ts)) + '</span>';
        var messageContent = "";
        if (userId == respUId) {
            messageContent = '<span class="bubble rightbubble">' + jsonObject.info + '</span>';
        } else {
            messageContent = '<span class="bubble leftbubble">' + jsonObject.info + '</span>';
        }
        writeToScreen(messageTime + messageContent);
    }

    function onError(evt) {
        writeToScreen('<span style="color: #f5222d;">发生错误:</span> ' + evt.data);
    }

    function doSend() {
        var messageContext = document.getElementById('message').innerHTML.trim();
        if (messageContext == '') {
            alert("输入信息为空");
            document.getElementById('message').focus();
            return false;
        }
        if (typeof websocket === "undefined") {
            alert("WebSocket还未连接或连接失败");
            return false;
        }
        if (websocket.readyState == 3) {
            alert("WebSocket已经关闭，请重新连接");
            return false;
        }
        document.getElementById('message').innerHTML = ''; // 清空 div 中的内容
        document.getElementById('message').focus();
        websocket.send(messageContext);
    }

    function writeToScreen(message) {
        var div = "<div class='newmessage' >" + message + "</div>";
        var d = $("#output")[0];
        var doScroll = d.scrollTop <= d.scrollHeight - d.clientHeight;
        $("#output").append(div);
        if (doScroll) {
            d.scrollTop = d.scrollHeight - d.clientHeight;
        }
    }

    function en(event) {
        var evt = event || window.event;
        if (evt.keyCode == 13) {
            doSend();
        }
    }

    <!------------------------------------------------------------- 标签图标 -->
    const emojiMapping = {};
    for (let i = 0; i < 44; i++) {
        const emojiUrl = `../img/emoji/${i}.png`;
        emojiMapping[i] = emojiUrl;
        $("#emojiPicker").append(`<img src="${emojiUrl}" onclick="insertEmoji('${i}');" style="cursor:pointer; margin:2px;">`);
    }

    function showEmojis() {
        var emojiPicker = document.getElementById('emojiPicker');
        emojiPicker.style.display = emojiPicker.style.display === 'block' ? 'none' : 'block';
    }

    function insertEmoji(emojiCode) {
        var messageInput = document.getElementById('message');
        const emojiUrl = emojiMapping[emojiCode];
        if (emojiUrl) {
            messageInput.innerHTML += `<img src="${emojiUrl}" alt="emoji" style="width: 20px; height: 20px; vertical-align: middle;">`;
        }
        document.getElementById('emojiPicker').style.display = 'none';
    }

    <!------------------------------------------------------------- 文件上传 -->
    function uploadImage() {
        var input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = function (event) {
            var file = event.target.files[0];
            if (file) {
                var formData = new FormData();
                formData.append('file', file);

                fetch('/api/upload', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code == 0) {
                            document.getElementById('message').innerHTML = ''; // 清空 div 中的内容
                            document.getElementById('message').focus();
                            console.log("123")
                            websocket.send("<img src=http://192.168.1.10:8080/" + result.data + "\" alt=\"Base64 Image\">");
                        } else {
                            alert('文件上传失败: ' + result.msg);
                        }
                    })
                    .catch(error => {
                        console.error('文件上传错误:', error);
                        alert('文件上传出错，请重试');
                    });
            }
        };
        input.click();
    }

    function startVoiceCall() {
        alert('语音通话功能暂未实现');
    }
</script>
</body>
</html>